<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="笔记标题" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入笔记标题"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="创建者" prop="creator">
          <el-input
            v-model="queryParams.creator"
            placeholder="请输入创建者"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="queryParams.categoryId" placeholder="笔记分类" clearable style="width: 200px">
            <el-option label="学习笔记" value="1" />
            <el-option label="工作笔记" value="2" />
            <el-option label="生活笔记" value="3" />
            <el-option label="其他" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <el-card class="toolbar-card">
      <el-row :gutter="16" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="Delete"
            :disabled="multiple"
            class="toolbar-button is-danger"
            @click="handleDelete"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            icon="Download"
            class="toolbar-button is-warning"
            @click="handleExport"
          >导出</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 笔记表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="noteList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="笔记标题" align="center" prop="title" :show-overflow-tooltip="true" />
        <el-table-column label="创建者" align="center" prop="creatorName" width="120" />
        <el-table-column label="分类" align="center" prop="categoryName" width="100" />
        <el-table-column label="标签" align="center" prop="tags" width="150">
          <template #default="scope">
            <el-tag
              v-for="tag in scope.row.tags"
              :key="tag"
              size="small"
              style="margin-right: 4px;"
            >
              {{ tag }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否分享" align="center" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isShared ? 'success' : 'info'">
              {{ scope.row.isShared ? '已分享' : '私有' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="协作者数量" align="center" prop="collaboratorCount" width="100" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最后编辑" align="center" prop="updateTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
          <template #default="scope">
            <div class="table-operation-wrapper">
              <el-button
                type="primary"
                icon="View"
                @click="handleView(scope.row)"
                class="table-operation-button is-primary"
                size="small"
              >查看</el-button>
              <el-button
                type="danger"
                icon="Delete"
                @click="handleDelete(scope.row)"
                class="table-operation-button is-danger"
                size="small"
              >删除</el-button>
              <el-dropdown @command="(command) => handleCommand(command, scope.row)">
                <el-button
                  type="warning"
                  class="table-operation-button is-warning"
                  size="small"
                >
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="handleCollaborators" icon="User">协作者</el-dropdown-item>
                    <el-dropdown-item command="handleVersions" icon="Clock">版本历史</el-dropdown-item>
                    <el-dropdown-item command="handleExportNote" icon="Download">导出笔记</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getNotePage, deleteNote } from '@/api/note'
import { useRouter } from 'vue-router'
import Pagination from '@/components/Pagination/index.vue'

const router = useRouter()

// 响应式数据
const loading = ref(true)
const ids = ref([])
const multiple = ref(true)
const total = ref(0)
const noteList = ref([])
const queryFormRef = ref()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: undefined,
  creator: undefined,
  categoryId: undefined
})

// 获取笔记列表
const getList = async () => {
  loading.value = true
  try {
    const response = await getNotePage(queryParams)
    if (response.code === 200) {
      noteList.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取笔记列表失败')
    }
  } catch (error) {
    console.error('获取笔记列表失败:', error)
    ElMessage.error('获取笔记列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  multiple.value = !selection.length
}

// 查看笔记
const handleView = (row) => {
  router.push(`/note/note/${row.id}/view`)
}

// 删除按钮操作
const handleDelete = (row) => {
  const noteIds = row.id ? [row.id] : ids.value
  ElMessageBox.confirm('是否确认删除笔记编号为"' + noteIds + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteNote(noteIds[0])
      getList()
      ElMessage.success('删除成功')
    } catch (error) {
      console.error('删除笔记失败:', error)
      ElMessage.error('删除笔记失败')
    }
  }).catch(() => {})
}

// 更多操作触发
const handleCommand = (command, row) => {
  switch (command) {
    case 'handleCollaborators':
      handleCollaborators(row)
      break
    case 'handleVersions':
      handleVersions(row)
      break
    case 'handleExportNote':
      handleExportNote(row)
      break
    default:
      break
  }
}

// 协作者管理
const handleCollaborators = (row) => {
  router.push(`/note/note/${row.id}/collaborators`)
}

// 版本历史
const handleVersions = (row) => {
  router.push(`/note/note/${row.id}/versions`)
}

// 导出笔记
const handleExportNote = (row) => {
  ElMessage.info('导出笔记功能开发中...')
}

// 导出按钮操作
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 时间格式化
const parseTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString()
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.search-card {
  margin-bottom: 16px;
}

.toolbar-card {
  margin-bottom: 16px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>
